package part15;

import java.util.Iterator;
import java.util.Random;

/**
 * @author wcj
 * @Date 2021/5/28 21:05
 * @Version 1.0
 */
public class Part156 implements Generator<Coffee>, Iterable<Coffee> {
    private Class[] types = {Latte.class, Mocha.class, Cappuccnio.class, Americano.class, Breve.class};
    private static Random random = new Random(47);

    public Part156() {
    }

    private int size = 0;

    public Part156(int sz) {
        this.size = sz;
    }

    @Override
    public Coffee next() {
        try {
            return (Coffee) types[random.nextInt(types.length)].newInstance();
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    @Override
    public Iterator<Coffee> iterator() {
        return new CoffeeIterator();
    }

    class CoffeeIterator implements Iterator<Coffee> {
        int count = size;

        @Override
        public boolean hasNext() {
            return count > 0;
        }

        @Override
        public Coffee next() {
            count--;
            return Part156.this.next();
        }
    }

    public static void main(String[] args) {
        Part156 gen = new Part156();
        for (int i = 0; i < 5; i++) {
            System.out.println(gen.next());
        }
        for (Coffee coffee : new Part156(5)) {
            System.out.println(coffee);
        }
    }

}

/**
 * 生成器,泛型接口和泛型类没什么差别
 * 通常泛型接口实现的生成器只有一个方法，和工厂模式类似，不同的点在于，工厂模式需要传递参数从而确定生成对象的类型
 * 但是生成器不需要传递参数就可以生成对象
 * 注意基本数据类型不能当泛型，不过因为java提供呢自动装箱和自动拆箱机制，因此int类型可以自动转换为Integer类型
 *
 * @param <T>
 */
interface Generator<T> {
    /**
     * next
     *
     * @return
     */
    T next();
}

class Coffee {
    private static long counter = 0;
    private final long id = counter++;

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + " " + id;
    }
}

class Latte extends Coffee {
}

class Mocha extends Coffee {
}

class Cappuccnio extends Coffee {
}

class Americano extends Coffee {
}

class Breve extends Coffee {
}
